Skip to main content

Basic Syntax

Learning Python Syntax

Understanding Python's syntax is similar to learning a new spoken language. Immersion and practice are key to becoming fluent:

  • Vocabulary: Learn Python's keywords and functions.
  • Grammar: Understand how to structure code correctly.
  • Practice: Write and run code regularly to build proficiency.

Data Types in Python

Data types define the kind of value a variable holds and what operations can be performed on it. Python has several built-in data types.

Strings (str)

  • Represent textual data enclosed in quotes.
  • Example: "Hello, World!"
  • Used for handling words, sentences, or any text.

Integers (int)

  • Represent whole numbers without fractions.
  • Example: 42
  • Used for counting, indexing, and discrete calculations.

Floats (float)

  • Represent real numbers with decimal points.
  • Example: 3.1415
  • Used for precise measurements and continuous calculations.

Determining Data Types

Use the type() function to check a value's data type:

type("Python")  # Output: <class 'str'>
type(2021) # Output: <class 'int'>
type(9.81) # Output: <class 'float'>

Operations with Data Types

Performing operations depends on data type compatibility. Mixing incompatible types can cause errors.

Numeric Operations

  • Addition: 5 + 3 # Output: 8
  • Subtraction: 5 - 3 # Output: 2
  • Multiplication: 5 * 3 # Output: 15
  • Division: 5 / 2 # Output: 2.5

String Operations

  • Concatenation: Combine strings using +.
    "Python " + "Programming"  # Output: "Python Programming"
  • Repetition: Repeat strings using *.
    "Echo! " * 3  # Output: "Echo! Echo! Echo! "

Mixing Data Types

Attempting operations between incompatible types (e.g., int and str) results in a TypeError.

Example of an Error

result = 5 + "five"  # Raises TypeError

Error Message:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Type Conversion

Converting data types allows for operations between otherwise incompatible types.

Implicit Conversion

Python automatically converts compatible types during operations.

Example

result = 4 + 3.0
print(result) # Output: 7.0
print(type(result)) # Output: <class 'float'>
  • The integer 4 is implicitly converted to a float 4.0.

Explicit Conversion

Manually convert data types using conversion functions.

Common Conversion Functions

  • Integer to String: str()
  • String to Integer: int()
  • String to Float: float()

Examples

# Converting integer to string
age = 30
print("I am " + str(age) + " years old.") # Output: I am 30 years old.

# Converting string to integer
year = "2021"
next_year = int(year) + 1
print(next_year) # Output: 2022

# Converting string to float
pi_str = "3.1415"
pi_float = float(pi_str)
print(pi_float) # Output: 3.1415

Variables and Expressions

Variables store data that can be manipulated through expressions.

Variables

  • Declaration: Assign a value using =.
    message = "Hello, Python!"
  • Usage: Use the variable name to access the value.
    print(message)  # Output: Hello, Python!

Expressions

Combine variables and values using operators to produce new values.

Arithmetic Expressions

length = 5
width = 3
area = length * width
print(area) # Output: 15

String Expressions

first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print(full_name) # Output: Ada Lovelace

Calculating the Area of a Triangle

Demonstrates combining variables, expressions, and type conversion.

Mathematical Formula

The area AA of a triangle is calculated as:

A=12×base×heightA = \frac{1}{2} \times \text{base} \times \text{height}

Python Implementation

base = 10
height = 5
area = 0.5 * base * height
print("The area of the triangle is " + str(area))
# Output: The area of the triangle is 25.0
  • Type Conversion: str(area) converts the numeric area to a string for concatenation.

Handling Errors

Errors provide feedback to improve code quality.

Common Error: TypeError

Occurs when an operation is applied to an inappropriate type.

Example

print("Result: " + 42)  # Raises TypeError

Error Message:

TypeError: can only concatenate str (not "int") to str

Debugging Steps

  1. Read the Error Message: Understand the type and cause.
  2. Check Data Types: Use type() to inspect variables.
  3. Apply Type Conversion: Convert variables to compatible types.

Corrected Code

print("Result: " + str(42))  # Output: Result: 42

Implicit vs. Explicit Conversion

Understanding when and how Python converts data types is crucial.

Implicit Conversion

  • Automatic: Python converts types during operations without explicit instruction.
  • Example:
    result = 7 + 2.5  # int and float
    print(result) # Output: 9.5

Explicit Conversion

  • Manual: Programmer converts types using functions.
  • Functions:
    • int(): Convert to integer.
    • float(): Convert to float.
    • str(): Convert to string.
  • Example:
    number = 10
    text = " apples"
    print(str(number) + text) # Output: 10 apples

Best Practices

  • Consistent Data Types: Keep operations within compatible types.
  • Type Awareness: Always know the data type you're working with.
  • Conversion Functions: Use explicit conversions to prevent errors.

Summary

Understanding and correctly using data types, variables, and type conversions in Python is foundational for effective programming. By mastering these basics, you set the stage for tackling more complex coding challenges with confidence.